<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="异常消息" prop="msg">
                <el-input v-model="queryParams.msg" placeholder="请输入异常消息" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="触发时间" prop="time">
                <el-date-picker v-model="dateRangeTime" type="datetimerange" range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期" placeholder="请选择触发时间"
                    value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime" clearable>
                </el-date-picker>
            </el-form-item>
            <el-form-item label="异常类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择异常类型" clearable style="width: 240px">
                    <el-option v-for="dict in log_error_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete"
                    v-hasFunc="'exception:log:del'">删除</el-button>
            </el-col>
            <right-toolbar :showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" highlight-current-row
            @row-dblclick="handleView">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="追踪id" align="center" prop="traceIdentifier" :show-overflow-tooltip="true"
                v-if="columns.showColumn('traceIdentifier')">
                <template #default="scope">
                    <el-tooltip content="点击追踪" placement="right">
                        <el-text type="primary" class="cursor-pointer hover:underline"
                            @click="handleTraceClick(scope.row.traceIdentifier)">
                            {{ scope.row.traceIdentifier }}
                        </el-text>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="接口名称" align="center" prop="actionName" :show-overflow-tooltip="true" width="200"
                v-if="columns.showColumn('actionName')">
                <template #default="scope">
                    {{ scope.row.traceInfo?.actionName }}
                </template>
            </el-table-column>
            <el-table-column label="触发时间" align="center" prop="time" :show-overflow-tooltip="true"
                v-if="columns.showColumn('time')">
                <template #default="scope">
                    {{ parseTime(scope.row.time) }}
                </template>
            </el-table-column>
            <el-table-column label="异常类型" align="center" prop="type" :show-overflow-tooltip="true"
                v-if="columns.showColumn('type')">
                <template #default="scope">
                    <dict-tag :options="log_error_type" :value="scope.row.type" />
                </template>
            </el-table-column>
            <el-table-column label="异常消息" align="center" prop="msg" :show-overflow-tooltip="true"
                v-if="columns.showColumn('msg')">
                <template #default="scope">
                    {{ scope.row.msg }}
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="primary" text icon="delete" @click="handleDelete(scope.row)"
                        v-hasFunc="'exception:log:del'">删除</el-button>
                    <el-button type="primary" text icon="view" @click="handleView(scope.row)"
                        v-hasFunc="'exception:log:info'">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改角色和菜单关联对话框 -->
        <el-drawer :title="title" v-model="open" width="500px" header-class="drawer-header">
            <el-descriptions title="基本信息" :column="1" border label-width="80px" style="margin-bottom: 30px;">
                <el-descriptions-item label="异常类型">
                    <dict-tag :options="log_error_type" :value="form.type" />
                </el-descriptions-item>
                <el-descriptions-item label="触发时间">{{ parseTime(form.time) }}</el-descriptions-item>
                <el-descriptions-item label="追踪id">{{ form.traceIdentifier }}</el-descriptions-item>
                <el-descriptions-item label="异常消息">{{ form.msg }}</el-descriptions-item>
            </el-descriptions>
            <el-collapse :model-value="['trace']" style="margin-bottom: 30px;">
                <el-collapse-item title="堆栈信息" name="trace">
                    <codemirror v-model="form.trace" :extensions="extensions" readonly />
                </el-collapse-item>
            </el-collapse>
            <el-descriptions title="追踪信息" :column="1" border label-width="80" style="margin-bottom: 30px;">
                <template v-if="form.traceInfo">
                    <el-descriptions-item label="请求地址">{{ form.traceInfo?.url }}</el-descriptions-item>
                    <el-descriptions-item label="接口名称">{{ form.traceInfo?.actionName }}</el-descriptions-item>
                    <el-descriptions-item label="请求时间">
                        {{ parseTime(form.traceInfo?.requestTime) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="响应时间">
                        {{ parseTime(form.traceInfo?.responseTime) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="耗时(ms)">{{ form.traceInfo?.duration }}</el-descriptions-item>
                    <el-descriptions-item label="操作地址">{{ form.traceInfo?.clientIP }}</el-descriptions-item>
                    <el-descriptions-item label="代理信息">{{ form.traceInfo?.userAgent }}</el-descriptions-item>
                </template>
            </el-descriptions>
            <el-empty v-if="!form.traceInfo" description="暂无追踪信息" :image-size="100" />
        </el-drawer>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { listSysExceptionLog, getSysExceptionLog, delSysExceptionLog, addSysExceptionLog, updateSysExceptionLog } from "@/api/log/sysexceptionlog.js";

import { Codemirror } from "vue-codemirror";
import { oneDark } from "@codemirror/theme-one-dark";


const extensions = [oneDark]

const { proxy } = getCurrentInstance()

//字典数据
const dicts = ["log_error_type"];
const dictRefs = proxy.useDict(...dicts);
const { log_error_type } = dictRefs;

//弹窗操作类型
//0:新增，1：修改，2:查看
const operateType = ref(0)
//表单ref
const formRef = ref();
// 遮罩层
const loading = ref(true);
// 选中数组
const selected = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 数据集
const dataList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);

//默认时间范围
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

//定义触发时间查询参数
const dateRangeTime = ref([]);




// 查询参数
const queryParams = reactive({
    pageIndex: 1,
    pageSize: 10,
    sort: "time",
    type: undefined,
    msg: undefined,
});



const state = reactive({
    single: true,
    multiple: true,
    form: {

    },
    rules: {

    },
    options: {
        typeOptions: [],
    }
})

const { form, rules, options, single, multiple } = toRefs(state)


//所有列
const columns = ref([
    { visible: true, prop: 'traceIdentifier', label: '追踪id' },
    { visible: true, prop: 'actionName', label: '接口名称' },
    { visible: true, prop: 'time', label: '触发时间' },
    { visible: true, prop: 'type', label: '异常类型' },
    { visible: true, prop: 'msg', label: '异常消息' },
]);

// 获取列表方法
const getList = () => {
    loading.value = true;
    //添加时间范围参数
    proxy.addDateRange(queryParams, dateRangeTime.value, 'Time');
    listSysExceptionLog(queryParams).then((response) => {
        dataList.value = response.result;
        total.value = response.totalNum;
        loading.value = false;
    });
};

// 重置表单
const reset = () => {

};

// 搜索按钮操作
const handleQuery = () => {
    queryParams.pageIndex = 1;
    getList();
};

// 重置按钮操作
const resetQuery = () => {
    reset();
    handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
    selected.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
    reset();
    operateType.value = 0;
    open.value = true;
    title.value = "添加数据";
};

// 修改按钮操作
const handleUpdate = (row) => {
    reset();
    operateType.value = 1;
    const key = row.id || selected.value;
    getSysExceptionLog(key).then((response) => {
        Object.assign(form.value, response);
        open.value = true;
        title.value = "修改数据";
    });
};


//查看
const handleView = (row) => {
    reset();
    operateType.value = 2;
    var key = row.id;
    getSysExceptionLog(key).then((response) => {
        Object.assign(form.value, response);
        open.value = true;
        title.value = "查看明细";
    });
}

// 提交按钮
const submitForm = () => {
    const validateForm = formRef.value?.validate;
    if (validateForm) {
        validateForm((valid) => {
            if (valid) {
                const apiCall = form.value.id ? updateSysExceptionLog : addSysExceptionLog;
                apiCall(form.value).then(() => {
                    proxy.$modal.msgSuccess("操作成功");
                    open.value = false;
                    getList();
                });
            }
        });
    }
};

//取消弹窗
const cancel = () => {
    open.value = false;
    proxy.resetForm("form")
}

// 删除按钮操作
const handleDelete = (row) => {
    const keys = [].concat(row.id || selected.value);
    proxy.$modal.confirm("是否确认删除编号为" + keys + "的数据项？")
        .then(() => delSysExceptionLog(keys))
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
};

// 导出按钮操作
const handleExport = () => {
    download("system//export", queryParams, `menu_${new Date().getTime()}.xlsx`);
};

// 页面加载时调用获取列表方法
onMounted(getList);


const handleTraceClick = (traceId) => {
    proxy.$router.push({
        path: '/message/operation',
        query: { traceIdentifier: traceId }
    })
}

</script>


<style lang="scss" scoped>
:deep(.drawer-header) {
    margin: 0;
}

// 新增光标和下划线样式
.cursor-pointer {
    cursor: pointer;
}

.hover\:underline:hover {
    text-decoration: underline;
}
</style>
